package com.gpj.demo.generate;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @className com.gpj.demo.generate.CodeGenerator
 * @description
 *   mybatis逆向工程
 * @author GPJ
 * @date 2021/4/20 9:33
 * @version 1.0
 **/
public class CodeGenerator {
	private static final String MYSQL_HOST = "172.19.83.133";
	private static final String MYSQL_PORT = "33006";
	private static final String MYSQL_SCHEMA = "partywork";
	private static final String[] TABLES = {"t_dic", "t_file", "t_organize", "t_partyer", "t_partyer_ext", "t_partyer_org", "t_partyer_org_histroy"};

	public static void main(String[] args) {
		CodeGenerator.generate();
	}

	/**
	 * 读取控制台内容
	 */
	public static String scanner(String tip) {
		Scanner scanner = new Scanner(System.in);
		StringBuilder help = new StringBuilder();
		help.append("请输入" + tip + "：");
		System.out.println(help.toString());
		if (scanner.hasNext()) {
			String ipt = scanner.next();
			if (StringUtils.isNotEmpty(ipt)) {
				return ipt;
			}
		}
		throw new MybatisPlusException("请输入正确的" + tip + "！");
	}

	public static void generate(){
		AutoGenerator mpg = new AutoGenerator();

		/* 全局配置 */
		GlobalConfig globalConfig = new GlobalConfig();
		String projectPath = System.getProperty("user.dir"); // 生成文件的输出目录
		globalConfig.setOutputDir(projectPath + "/src/main/java");
		globalConfig.setAuthor("广鹏举"); // Author设置作者
		globalConfig.setFileOverride(true); // 是否覆盖文件
		globalConfig.setOpen(false); // 生成后打开文件
		globalConfig.setEntityName("%sEntity");
		mpg.setGlobalConfig(globalConfig);

		/* 数据源配置 */
		DataSourceConfig dataSourceConfig = new DataSourceConfig();
		dataSourceConfig.setDbType(DbType.MYSQL);
		//自定义数据类型转换
		dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
		dataSourceConfig.setUrl("jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_SCHEMA + "?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false");
		dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
		dataSourceConfig.setUsername("founder");
		dataSourceConfig.setPassword("1234");
		mpg.setDataSource(dataSourceConfig);

		/* 包配置 */
		PackageConfig pc = new PackageConfig();
		pc.setModuleName("com.founder.comsrv.partywork");
		pc.setParent("core");
		mpg.setPackageInfo(pc);


		/* 自定义配置 */
		InjectionConfig cfg = new InjectionConfig() {
			@Override
			public void initMap() {
				// to do nothing
			}
		};

		/* 模板 */
		//如果模板引擎是 freemarker
		String templatePath = "/templates/mapper.xml.ftl";
		// 如果模板引擎是 velocity
		// String templatePath = "/templates/mapper.xml.vm";


		/* 自定义输出配置 */
		List<FileOutConfig> focList = new ArrayList<>();
		// 自定义配置会被优先输出
		focList.add(new FileOutConfig(templatePath) {
			@Override
			public String outputFile(TableInfo tableInfo) {
				// 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
				return projectPath + "/src/main/resources/mapper/" +
						"/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
			}
		});
		cfg.setFileOutConfigList(focList);
		mpg.setCfg(cfg);

		/* 配置模板 */
		TemplateConfig templateConfig = new TemplateConfig();

		// 配置自定义输出模板
		//指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
		 templateConfig.setEntity("template/MyEntity.java");
		// templateConfig.setService();
		 templateConfig.setController(""); // 设置不生成controller

		templateConfig.setXml(null);
		mpg.setTemplate(templateConfig);

		/**
		 * 策略配置
		 */
		StrategyConfig strategy = new StrategyConfig();
		//设置命名格式
		strategy.setNaming(NamingStrategy.underline_to_camel);
		strategy.setColumnNaming(NamingStrategy.underline_to_camel);
		strategy.setInclude(TABLES);
		//实体是否为lombok模型（默认 false）
		strategy.setEntityLombokModel(true);
		//生成 @RestController 控制器
//		strategy.setRestControllerStyle(false);
		//设置自定义继承的Entity类全称，带包名
		//strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity");
		//设置自定义继承的Controller类全称，带包名
		//strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController");
		//设置自定义基础的Entity类，公共字段
//		strategy.setSuperEntityColumns("id");
		//驼峰转连字符
		strategy.setControllerMappingHyphenStyle(true);

		strategy.setEntityTableFieldAnnotationEnable(true);
		//表名前缀
		strategy.setTablePrefix("t_");
		strategy.setFieldPrefix("[a-zA-Z]+_");
		mpg.setStrategy(strategy);
		mpg.setTemplateEngine(new FreemarkerTemplateEngine());
		mpg.execute();
	}
}